var submit = 2
layui.use(['table', 'admin', 'ax','laydate','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var form = layui.form;

    laydate.render({
      elem: '#startTime'
        	,value:new Date()
    });

    laydate.render({
      elem: '#endTime'
        	,value:new Date()
    });

    /**
     * 调度单表管理
     */
    var TDispatch = {
        tableId: "tDispatchTable"
    };

    /**
     * 回传单表管理
     */
    var TransportReceipt = {
        tableId: "transportReceiptTable"
    };
    
    /**
     * 初始化表格的列
     */
    TDispatch.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键id'},
            {field: 'operateName', sort: true, title: '项目', style:'font-weight: 600;'},
            {field: 'trainNumber', sort: true, title: '车次', style:'font-weight: 600;'},
            {field: 'tstate', sort: true, title: '运输状态', style:'font-weight: 600;',
            	templet: function(d){
            		var str = "";
            		if (d.tstate == '运输中'){
                    	str += '<i class="layui-icon" lay-event="tooTstateDetailed" style="color: #2b85e4;">&#xe615;</i><span style="color:#ffaa00;font-weight: bold;">' + d.tstate + '</span>'
					} else if (d.tstate == '已完成'){
                    	str += '<i class="layui-icon" lay-event="tooTstateDetailed" style="color: #2b85e4;">&#xe615;</i><span style="color:#19be6b;font-weight: bold;">' + d.tstate + '</span>'
					} else {
                    	str += '<i class="layui-icon" lay-event="tooTstateDetailed" style="color: #2b85e4;">&#xe615;</i><span style="font-weight: bold;">' + d.tstate + '</span>'
					}
            		return str
            	}
			},
            {field: 'startDate', sort: true, title: '发车日期', style:'font-weight: 600;'},
            {field: 'dispatchNumber', sort: true, title: '运输单号', style:'font-weight: 600;',templet: '#dispatchNumberTpl',width: 180},
            {field: 'carnumber', sort: true, title: '车号', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'siji', sort: true, title: '司机', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'sijidianhua', sort: true, title: '电话', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'chexing', sort: true, title: '车型', style:'background-color: #dbf1e1;font-weight: 600;'},

            {field: 'zhunzailiang', sort: true, title: '准载体积', style:'font-weight: 600;'},
            {field: 'fulllv', sort: true, title: '满载率%', style:'font-weight: 600;', totalRowText: '合计：'},
            {align: 'center', sort: true, toolbar: '#tableBar4', title: '装载照片'},
            {field: 'toovolume', sort: true, title: '总体积m3', style:'font-weight: 600;', totalRow: true},
            {field: 'tooNum', sort: true, title: '总数量', style:'font-weight: 600;', totalRow: true},
            {field: 'matrixingNumber', sort: true, title: '换算数量', style:'font-weight: 600;', totalRow: true},
            {field: 'toomoney', sort: true, title: '货值', style:'font-weight: 600;', totalRow: true},
            {field: 'chengyunfangshi', sort: true, title: '承运方式', style:'font-weight: 600;'},
            {field: 'lineName', sort: true, title: '线路', style:'font-weight: 600;'},
            {field: 'dianduyuan', sort: true, title: '调度员', style:'font-weight: 600;'},
            {field: 'createTime', sort: true, title: '调度时间', style:'font-weight: 600;'},
            {field: 'examineName', sort: true, title: '审核人', style:'font-weight: 600;'},
            {field: 'examineTimes', sort: true, title: '审核时间', style:'font-weight: 600;'},
            {field: 'fayunTimes', sort: true, title: '发运时间', style:'font-weight: 600;'},
            {field: 'completeName', sort: true, title: '完成人', style:'font-weight: 600;'},
            {field: 'completeTimes', sort: true, title: '完成时间', style:'font-weight: 600;'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    TDispatch.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['tstate'] = $("#tstate").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['carnumber'] = $("#carnumber").val();
        queryData['driver1'] = $("#driver1").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['carrierId'] = $("#carrierId").val();
        table.reload(TDispatch.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + TDispatch.tableId,
        url: Feng.ctxPath + '/tDispatch/list',
        page: true,
        limit: 240,
		limits:[60,120,240,360,480,600],
        height: 400,
        totalRow: true,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        defaultToolbar: ['filter', 'exports', 'print'],
        cellMinWidth: 100,
        cols: TDispatch.initColumn()
    });

    // 在途监控按钮点击事件
    $('#monitoring').click(function () {
		window.open('http://39.105.212.172:16061/manager.html');
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        TDispatch.search();
    });

    //查询库区
    form.on('select(operateId)',function(){
        $("#carrierId").empty();
        $.ajax({
            url:Feng.ctxPath + '/basicCarrier/Querylist',
            dataType:"json",   //返回格式为json
            async: false,
            data:{"operateId":$("#operateId").val()},    //参数值
            type:"post",   //请求方式
            success:function(data){
                if(data.length>0){
                    var str = "<option value=''>选择承运商</option>";
                    $.each(data,function(key,value){
                        str += "<option value='"+value.id+"'>"+value.carrierName+"</option>";
                    });
                    $("#carrierId").html(str);
                }
            }
        });
        form.render('select');
    });

    // 工具条点击事件
    table.on('tool(' + TDispatch.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'tooTstateDetailed') {
            layer.open({
                type: 2,
                title: '运输信息',
                area: ['1100px', '500px'],
                anim: 5,
                content: Feng.ctxPath + '/transportMsg?dispatchNumber=' + data.dispatchNumber,
            });
        } else if (layEvent === 'tooDetailed') {
            layer.open({
                type: 2,
                title: '配送派车信息',
                area: ['1250px', '570px'],
                anim: 5,
                content: Feng.ctxPath + '/tDispatch/tooDetailed2?dispatchNumber=' + data.dispatchNumber,
            });
        } else if (layEvent === 'paymentProve') {
  	    	//构建图像数组
      		var items = [];
        	if (data.zhuangzaiFileid!='') {
        		var obj = {};
        		obj.src = '/system/previewa/' + data.zhuangzaiFileid;
        		obj.title = '预览图片';
        		items.push(obj)
    	      	//定义选项（如果需要）
    	      	var options = {
    	      	    index: 0 // 此选项表示您将从第一张图片开始
    	      	};
    	      	//初始化插件
    	      	var viewer = new PhotoViewer(items, options);
			} else {
                Feng.info("暂无照片!");
			}
        } 
    });

    /**
     * 初始化表格的列
     */
    TransportReceipt.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键id'},
            {align: 'center', toolbar: '#tableBarde', title: '操作'},
            {field: 'stockPort', title: '备货口', style:'background-color: #ecf5ff;font-weight: 600;'},

            {field: 'getUnit', title: '单位', style:'background-color: #dbf1e1;font-weight: 600;', width: 140},
            {field: 'getLocation', title: '地址', style:'background-color: #dbf1e1;font-weight: 600;', width: 160},
            {field: 'getPeople', hide: true, title: '联系人', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'getTel', hide: true, title: '联系电话', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'kilometer', title: '公里数', style:'font-weight: 600;'},

            {field: 'num', sort: true, title: '数量'},
            {field: 'volume', title: '体积'},

            {field: 'sdtstate', sort: true, title: '送达状态', style:'font-weight: 600;'},
            {field: 'sdfileId', title: '电子签名',templet: '#sdpaymentProveTpl', event: 'sdpaymentProve'},
            {field: 'sdtime', sort: true, title: '送达时间'},
            {field: 'sdusername', title: '送达人员'},

            {field: 'tstate', sort: true, title: '回单状态', style:'font-weight: 600;'},
            {field: 'fileId', title: '回单',templet: '#paymentProveTpl', event: 'paymentProve'},
            {field: 'time', sort: true, title: '回传时间'},
            {field: 'username', title: '回传人员'},
        ]];
    };

    // 单击行事件
    table.on('row(' + TDispatch.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + TDispatch.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + TDispatch.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        	receipt(data);
    });
    
    function receipt(data){
    	var dispatchNumber;
    	if (data!=null) {
    		dispatchNumber = data.dispatchNumber;
		} else {
			dispatchNumber = 'nodata';
		}

        // 渲染表格
        var tableResult = table.render({
            elem: '#' + TransportReceipt.tableId,
            url: Feng.ctxPath + '/transportReceipt/list?dispatchNumber='+dispatchNumber+'&condition='+'',
            page: true,
            limit: 20,
            height: 370,
	        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
	        defaultToolbar: ['filter', 'exports', 'print'],
            cellMinWidth: 100,
            cols: TransportReceipt.initColumn()
        });

        // 工具条点击事件
        table.on('tool(' + TransportReceipt.tableId + ')', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (obj.event === 'paymentProve') {
      	    	//构建图像数组
	      		var items = [];
	        	if (data.fileId!='') {
            		var obj = {};
            		obj.src = '/transportReceipt/show?fileId=' + data.fileId;
            		obj.title = '预览图片';
            		items.push(obj)
	    	      	//定义选项（如果需要）
	    	      	var options = {
	    	      	    index: 0 // 此选项表示您将从第一张图片开始
	    	      	};
	    	      	//初始化插件
	    	      	var viewer = new PhotoViewer(items, options);
				} else {
	                Feng.info("暂无照片!");
				}
            } else if (obj.event === 'sdpaymentProve') {
      	    	//构建图像数组
	      		var items = [];
	        	if (data.sdfileId!='') {
            		var obj = {};
            		obj.src = '/transportReceipt/show?fileId=' + data.sdfileId;
            		obj.title = '预览图片';
            		items.push(obj)
	    	      	//定义选项（如果需要）
	    	      	var options = {
	    	      	    index: 0 // 此选项表示您将从第一张图片开始
	    	      	};
	    	      	//初始化插件
	    	      	var viewer = new PhotoViewer(items, options);
				} else {
	                Feng.info("暂无照片!");
				}
            } else if (obj.event === 'huowu'){
                layer.open({
                    type: 2,
                    title: '货物明细',
                    area: ['1100px', '500px'],
                    anim: 5,
                    content: Feng.ctxPath + '/transportDispatch?dispatchNumber=' + data.dispatchNumber+'&getUnitid='+data.getUnitid + '&getLocationid=' + data.getLocationid,
                });
            } 
        });
    };
});
